package com.ask.socket;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class URSProtocol {

    private String URS;
    private Package[] pckg = Package.getPackages();
    private Method method = null;
    private Object o = null;

    public URSProtocol(String urs) {
        this.URS = urs;
    }

    public void IOProtocol() {
        // Split string delimiter "/" class/function/args
        String[] tempURS = URS.split("/");

        for (final Package p : pckg) {
            final String pack = p.getName();
            // class {Class/}
            final String tentative = pack + "." + tempURS[0];
            try {
                Class<?> t = Class.forName(tentative);
                o = t.newInstance();
                System.out.println(tempURS.length);
                switch (tempURS.length) {
                    case 2:
                        // function {/function}
                        method = t.getDeclaredMethod(tempURS[1], new Class[]{});
                        System.out.println(tempURS[1]);
                        System.out.println(method.invoke(o) + " :: class String");
                        break;
                    case 3:
                        method = t.getDeclaredMethod(tempURS[1], new Class[]{});
                        System.out.println(tempURS[2]);
                        System.out.println(method.invoke(o, tempURS[2])
                                + " :: class String with args");
                        break;
                }
                System.out.println("this is my instance:" + o.toString());
                System.out.println(tempURS[0]);
            } catch (IllegalAccessException iae) {
            } catch (InstantiationException ie) {
            } catch (InvocationTargetException ite) {
            } catch (SecurityException e) {
            } catch (NoSuchMethodException e) {
            } catch (final ClassNotFoundException e) {
                System.out.println("Class Not Found");
                continue;
            }
            System.out.println(pack);
            break;
        }
    }

    public static void main(String[] args) {
        new URSProtocol("mainSocket/setMain").IOProtocol();
        System.out.println();

    }

    public Object getMethod() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
        return method.invoke(o);
    }
    // format String array Split Delimiter ";"
    // atur susunan disini
}
